#include "Config.h"
#include "FileIO_Pkg.h"

Config::Config() {}

Config::Config(const std::string& file) { this->file = file; }

bool Config::Load() {
    std::string text;
    try {
        text = TryReadAllString(file, 0, 0, "r");
    }
    catch (...) {
        return false;
    }
    return Load(text);
}

bool Config::Load(std::string text) {
    std::string name;
    auto lines = Split(text, "\n");
    for (const auto& i : lines) {
        text = Trim(i);
        if (text != "") {
            if (text[0] == '[') {
                auto n = text.find("]", 1);
                if (n != -1) {
                    name = text.substr(1, n - 1);
                }
            }
            else {
                auto t = text.find("=");
                if (t != -1 && t != 0 && t + 1 < text.size()) {
                    Set(name, Trim(text.substr(0, t)), text.substr(t + 1));
                }
            }
        }
    }
    return true;
}

bool Config::Store() { return WriteAll(file, StoreString()); }
